package module.map.fileTabs
{
	import drongo.model.events.ModelEvent;

	import flash.events.Event;

	import common.view.FGUIMediator;

	import fairygui.GObject;
	import fairygui.event.ItemEvent;

	import module.map.model.MapModel;
	import module.map.model.ProjectModel;

	import robotlegs.bender.extensions.mediatorMap.api.IMediatorMap;

	import ui.Basic.UI_FileTabButton;
	import ui.Map.UI_FileTabPanel;

	public class FileTabMediator extends FGUIMediator
	{
		[Inject]
		public var view:UI_FileTabPanel;
		[Inject]
		public var project:ProjectModel;
		[Inject]
		public var mediatorMap:IMediatorMap;

		public function FileTabMediator()
		{
			super();
		}

		override public function initialize():void
		{
			super.initialize();
			this.view.m_list.itemRenderer = ListItemRender;
			this.AddEvents();
			this.Refresh();
		}

		override public function destroy():void
		{
			super.destroy();
			this.RemoveEvents();
		}

		private function Refresh():void
		{
			this.view.m_list.removeChildrenToPool();
			this.view.m_list.numItems = project.openList.length;
			if (this.project.currentMap != null)
			{
				var index:int = this.project.openList.GetChildIndex(this.project.currentMap);
				this.view.m_list.selectedIndex = index;
			}
		}

		private function ListItemRender(index:int, obj:GObject):void
		{
			var item:FileTabButton = obj as FileTabButton;
			item.Init(this.project.openList.GetAt(index) as MapModel, this.project);
		}

		private function AddEvents():void
		{
			this.project.addEventListener(Event.CHANGE, this.SwithMapHandler);
			this.project.openList.addEventListener(ModelEvent.ADD_CHILD, this.OpenListChanged);
			this.project.openList.addEventListener(ModelEvent.REMOVE_CHILD, this.OpenListChanged);
			this.view.m_list.addEventListener(ItemEvent.CLICK, this.ListItemClick);
		}

		private function RemoveEvents():void
		{
			this.project.removeEventListener(Event.CHANGE, this.SwithMapHandler);
			this.project.openList.removeEventListener(ModelEvent.ADD_CHILD, this.OpenListChanged);
			this.project.openList.removeEventListener(ModelEvent.REMOVE_CHILD, this.OpenListChanged);
			this.view.m_list.removeEventListener(ItemEvent.CLICK, this.ListItemClick);
		}

		private function ListItemClick(e:ItemEvent):void
		{
			this.project.currentMap = this.project.openList.GetAt(this.view.m_list.selectedIndex) as MapModel;
		}

		private function SwithMapHandler(e:Event):void
		{
			this.view.m_list.selectedIndex = this.project.openList.GetChildIndex(this.project.currentMap);
		}

		private function OpenListChanged(e:Event):void
		{
			this.Refresh();
		}
	}
}